package com.betterjr.modules.commission.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.betterjr.common.mapper.JsonMapper;
import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.BetterStringUtils;
import com.betterjr.common.utils.Collections3;
import com.betterjr.common.utils.UserUtils;
import com.betterjr.mapper.pagehelper.Page;
import com.betterjr.modules.commission.dao.CommissionPayBankResultMapper;
import com.betterjr.modules.commission.entity.CommissionBusPaymentCode;
import com.betterjr.modules.config.dubbo.interfaces.IDomainAttributeService;
import com.betterjr.modules.document.entity.CustFileItem;
import com.betterjr.modules.flie.service.JxlsFileService;

/**
 * 
 * @ClassName: CommissionPayBankResultService 
 * @Description: TODO(直通车代码) 
 * @author chenlq
 * @date 2017年10月17日 下午1:53:46 
 *
 */
@Service
public class CommissionPayBankResultService
        extends BaseService<CommissionPayBankResultMapper, CommissionBusPaymentCode> {

    /*@Reference(interfaceClass = ICustMechBaseService.class)
    private ICustMechBaseService custMechBaseService;
    */
    @Autowired
    private CommissionPayBankRecordService commissionPayBankRecordService;

    @Reference(interfaceClass = IDomainAttributeService.class)
    private IDomainAttributeService domainAttributeDubboClientService;

    @Autowired
    private JxlsFileService jxlsFileService;

    /**
     * 
     * @Title: queryCommissionPayBankResult 
     * @Description: TODO(查询直通车代码信息) 
     * @param @param anMap
     * @param @param anFlag
     * @param @param anPageNum
     * @param @param anPageSize
     * @param @return 参数说明 
     * @return Page<CommissionBusPaymentCode> 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年10月20日 上午11:19:13
     */
    public Page<CommissionBusPaymentCode> queryCommissionPayBankResult(Map<String, Object> anMap, String anFlag,
            int anPageNum, int anPageSize) {
        // 过滤数据
        anMap = Collections3.filterMapEmptyObject(anMap);
        if (Collections3.isEmpty(anMap)) {
            anMap.put("GTEregDate", "19750101");
            anMap.put("LTEregDate", "29750101");
        }
        // 模糊查询
        if (anMap.containsKey("bankFullName")) {
            anMap = Collections3.fuzzyMap(anMap, new String[] { "bankFullName" });
        }
        final Page<CommissionBusPaymentCode> page = this.selectPropertyByPage(anMap, anPageNum, anPageSize,
                "1".equals(anFlag), "id desc");
        return page;
    }

    /**
     * 
     * @Title: saveAddBankPayCodeInfo 
     * @Description: TODO(新增直通车代码信息) 
     * @param @param anBankPayCodeInfo
     * @param @return 参数说明 
     * @return CommissionBusPaymentCode 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年10月20日 上午11:19:54
     */
    public CommissionBusPaymentCode saveAddBankPayCodeInfo(CommissionBusPaymentCode anBankPayCodeInfo) {
        // 初始化默认信息
        anBankPayCodeInfo.initAddValue(UserUtils.getOperatorInfo());

        // 检验新增数据是否为空
        BTAssert.notNull(anBankPayCodeInfo, "新增银行直通车代码失败，保存的数据为空，请确保已输入内容。");
        BTAssert.notNull(anBankPayCodeInfo.getPaymentNo(), "新增银行直通车代码失败，银行直通车代码不能为空！");
        BTAssert.notNull(anBankPayCodeInfo.getBankShortName(), "新增银行直通车代码失败，银行简称不能为空！");
        // 判断直通车代码只能是数字
        final String regexNum = "\\d+";
        BTAssert.isTrue(anBankPayCodeInfo.getPaymentNo().matches(regexNum), "银行直通车代码只能是数字，请重新输入！");
        // 是否存在相同直通车代码全称
        final CommissionBusPaymentCode insertCodeName = new CommissionBusPaymentCode();
        insertCodeName.setBankFullName(anBankPayCodeInfo.getBankFullName());
        final CommissionBusPaymentCode existPayCode = this.selectOne(insertCodeName);
        if (existPayCode != null) {
            BTAssert.notNull(null, "直通车代码银行全称不能有重复的，银行全称不允许重复，新增失败！");
        }

        // 是否存在相同直通代码
        final CommissionBusPaymentCode insertCode = new CommissionBusPaymentCode();
        insertCode.setBankFullName(anBankPayCodeInfo.getPaymentNo());
        final CommissionBusPaymentCode exist = this.selectOne(insertCode);
        if (exist != null) {
            BTAssert.notNull(null, "存在相同的直通车代码，直通车代码不允许重复，新增失败！");
        }

        // 把旧的直通车银行支付文件变无效
        final CommissionBusPaymentCode bankPayCode = new CommissionBusPaymentCode();
        final Map<String, Object> map = new HashMap<String, Object>();
        map.put("batchNo", 0l);
        final Long fileValid = 0l;
        bankPayCode.setFileValid(fileValid);
        this.updateByExampleSelective(bankPayCode, map);

        logger.info("Begin to add saveAddBankPayCodeInfo 数据为：" + anBankPayCodeInfo + " 操作用户为："
                + UserUtils.getOperatorInfo().getName());
        this.insertSelective(anBankPayCodeInfo);
        // 调用excel文件生成方法
        createExcelFile(anBankPayCodeInfo);
        return anBankPayCodeInfo;
    }

    /**
     * 
     * @Title: saveUpdataBankPayCodeInfo 
     * @Description: TODO(修改直通车代码信息) 
     * @param @param anBankPayCodeInfo
     * @param @return 参数说明 
     * @return CommissionBusPaymentCode 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年10月20日 下午4:48:09
     */
    public CommissionBusPaymentCode saveUpdataBankPayCodeInfo(CommissionBusPaymentCode anBankPayCodeInfo) {

        // 检验新增数据是否为空
        BTAssert.notNull(anBankPayCodeInfo, "编辑银行直通车代码失败，保存的数据为空，请确保已输入内容。");
        BTAssert.notNull(anBankPayCodeInfo.getPaymentNo(), "编辑银行直通车代码失败，银行直通车代码不能为空！");
        BTAssert.notNull(anBankPayCodeInfo.getBankShortName(), "编辑银行直通车代码失败！银行简称为空");
        // 判断直通车代码只能是数字
        final String regexNum = "\\d+";
        BTAssert.isTrue(anBankPayCodeInfo.getPaymentNo().matches(regexNum), "银行直通车代码只能是数字，请重新输入！");

        logger.info("Begin to saveUpdateInvoiceCustInfo 数据为：" + anBankPayCodeInfo + " 操作用户为："
                + UserUtils.getOperatorInfo().getName());
        final CommissionBusPaymentCode BankPayCodeInfo = this.selectByPrimaryKey(anBankPayCodeInfo.getId());
        BTAssert.notNull(BankPayCodeInfo, "修改银行直通车代码失败！没有查询到修改的记录");
        // 判断传入的值不与之前相等
        if (!BankPayCodeInfo.getPaymentNo().equals(anBankPayCodeInfo.getPaymentNo())) {
            BankPayCodeInfo.setPaymentNo(anBankPayCodeInfo.getPaymentNo());
        }

        if (!BankPayCodeInfo.getBankFullName().equals(anBankPayCodeInfo.getBankFullName())) {
            BankPayCodeInfo.setBankFullName(anBankPayCodeInfo.getBankFullName());
        }

        if (!BankPayCodeInfo.getBankShortName().equals(anBankPayCodeInfo.getBankShortName())) {
            BankPayCodeInfo.setBankShortName(anBankPayCodeInfo.getBankShortName());
        }

        // 初始化信息
        BankPayCodeInfo.initModifyValue(UserUtils.getOperatorInfo());
        this.updateByPrimaryKeySelective(BankPayCodeInfo);
        logger.info("end to saveUpdateInvoiceCustInfo 数据为：" + BankPayCodeInfo + " 操作用户为："
                + UserUtils.getOperatorInfo().getName());

        // 把修改前的直通车银行支付文件变无效
        final CommissionBusPaymentCode bankPayCode = new CommissionBusPaymentCode();
        final Map<String, Object> map = new HashMap<String, Object>();
        map.put("batchNo", 0l);
        final Long fileValid = 0l;
        bankPayCode.setFileValid(fileValid);
        this.updateByExampleSelective(bankPayCode, map);

        // 调用excel文件生成方法
        createExcelFile(BankPayCodeInfo);
        return BankPayCodeInfo;

    }

    /**
     * 
     * @Title: createExcelFile 
     * @Description: TODO(银行直通车代码excel文件生成) 
     * @param @param anBankPayCodeInfo 参数说明 
     * @return void 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年10月25日 上午9:01:22
     */
    public void createExcelFile(CommissionBusPaymentCode anBankPayCodeInfo) {
        // 根据文件模版生成excel文件
        final String bankPayCodeExportTemplate = domainAttributeDubboClientService
                .findString("GLOBAL_BANK_PAY_CODE_EXPORT_TEMPLATE");
        logger.info("bankPayCodeExportTemplate:" + bankPayCodeExportTemplate + " 操作用户为："
                + UserUtils.getOperatorInfo().getName());
        Long fileId = 0l;
        String fileType = "";
        if (bankPayCodeExportTemplate != null) {
            final Map<String, Object> templateMp = JsonMapper.parserJson(bankPayCodeExportTemplate);
            fileId = Long.parseLong(templateMp.get("id").toString());
            fileType = (String) templateMp.get("fileType");
            if (BetterStringUtils.isBlank(fileType)) {
                fileType = ".xlsx";
            }
        }

        // 查出直通车支付码信息
        final List<CommissionBusPaymentCode> bankPayCodeList = this.selectAll();
        logger.info("CommissionBusPaymentCodeInfo数据为：" + bankPayCodeList + " 操作用户为："
                + UserUtils.getOperatorInfo().getName());
        // 生成文件
        final Map<String, Object> fileMap = new HashMap<String, Object>();
        fileMap.put("bankPayCodeList", bankPayCodeList);
        try {
            final CustFileItem custFile = jxlsFileService.transformXLSFileToList(fileMap, fileId, "银行直通车代码" + fileType);
            // 设置直通车代码文件最新信息，把最新文件记录变为有效
            final Long fileValid = 1l;
            logger.info("生成后的文件，custFile:" + custFile);
            anBankPayCodeInfo.setFileId(custFile.getId());
            anBankPayCodeInfo.setBatchNo(custFile.getBatchNo());
            anBankPayCodeInfo.setFileValid(fileValid);
            this.updateByPrimaryKey(anBankPayCodeInfo);
        }
        catch (final Exception e) {
            logger.error("异常：", e);
        }
    }

}
